<?php

// wiki
// GET wiki
// @param key 访问密匙
// http://dt.51dojob.com/api?wiki&key=51dojob
// http://dt.io/api?wiki&key=51dojob

namespace app\api\resource;

class Wiki
{
    // 方法
    public $_method = ['GET'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description  = '文档';
    // 参数
    public $_param  = [
        'key' => '访问密匙',
    ];
    // 返回
    public $_return = [
        200 => '请求成功',
        403 => '授权密匙必需',
        422 => '授权密匙不正确',
    ];

    public function run(&$request)
    {
        $key = $request->get('key/s','');
        if ( empty($key) ) return [403,'授权密匙必需'];
        if ( '51dojob' != $key ) return [422,'授权密匙不正确'];

        $dir = ROOT_PATH . 'app' . DS . 'api' . DS . 'resource';
        $arr = $this->_loop($dir);
        if ( empty($arr) ) return [ 200,[] ];
        $ret = $this->_handle($arr);

        return [200,$ret];
    }

    // 循环资源
    private function _loop($dir, &$ret = [])
    {
        $dirArr = $this->_scan($dir);
        foreach ($dirArr as $key => $val) {
            $file = $dir . DS . $val;
            if ( is_dir($file) ) {
                $this->_loop($file,$ret);
            } else {
                $ret[] = $file;
            }
        }
        return $ret;
    }

    // 扫描目录
    private function _scan($dir)
    {
        $dirArr = scandir($dir);
        unset($dirArr[0],$dirArr[1]);
        sort($dirArr);
        return $dirArr;
    }

    // 解析接口名
    private function _analy($dir)
    {
        $arr = explode(DS,$dir);
        $ret = '';
        foreach($arr as $key => $val) {
            $ret .= ( (0 === $key) ? '' : '.' ) . lcfirst($val);
        }
        return $ret;
    }

    // 文档内容处理
    private function _handle($arr)
    {
        $ret = [];
        foreach($arr as $key => $val) {
            preg_match('/app(.*)\.php/',$val,$matches);
            $file = "app" . $matches[1];
            preg_match('/resource\\' . DS . '(.*)/',$file,$matches);
            $name = $this->_analy($matches[1]);
            $file = str_replace('/','\\',$file);
            $class = new $file;

            $ret[$name]['api']         = $name;
            $ret[$name]['description'] = isset($class->_description) ? $class->_description : '';
            $ret[$name]['method']      = isset($class->_method) ? $class->_method : [];
            $ret[$name]['pre']         = isset($class->_pre) ? $class->_pre : [];
            $ret[$name]['param']       = isset($class->_param) ? $class->_param : [];
            $ret[$name]['return']      = isset($class->_return) ? $class->_return : [];
            unset($class);
        }
        return $ret;
    }
}